package com.jwthhealth_pub.old.sign.presenter;

import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.jwthhealth_pub.R;
import com.jwthhealth_pub.app.App;
import com.jwthhealth_pub.common.preference.PreferenceKey;
import com.jwthhealth_pub.old.api.ApiHelper;
import com.jwthhealth_pub.old.common.Constant;
import com.jwthhealth_pub.old.sign.model.CodeModel;
import com.jwthhealth_pub.old.sign.model.LoginModel;
import com.jwthhealth_pub.old.sign.model.SignUpModel;
import com.jwthhealth_pub.old.sign.view.SignInActivity;
import com.jwthhealth_pub.old.signutil.model.SendSms;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.jwthhealth_pub.old.sign.view.SignInActivity.SEND_SMS;


public class ISignInPresenterCompl implements ISignInPresenter {

    private SignInActivity mActivity;

//    Oauth2AccessToken mAccessToken;
//    private SsoHandler mSsoHandler;
//    private IUiListener QQLoginListener = new IUiListener() {
//
//        @Override
//        public void onComplete(final Object o) {
//            new Thread() {
//                @Override
//                public void run() {
//                    super.run();
//                    Log.d("ISignInPresenterCompl", o.toString());
//                    JSONObject jsonObject = null;
//                    try {
//                        jsonObject = new JSONObject(o.toString());
//                        final String openid = jsonObject.getString("openid");
//                        String expires_in = jsonObject.getString("expires_in");
//                        final String access_token = jsonObject.getString("access_token");
//
//
////                        String qqUnionId = ApiHelper.getQQUnionId(access_token);
//
////                        String request = ApiHelper.request(qqUnionId);
////                        Log.d("ISignInPresenterCompl", request);
////                        String replace = request.replace("callback(", "");
////                        String replaceJson = replace.replace(")", "");
////
////                        JSONObject unionJson = new JSONObject(replaceJson);
////                        String unionid = unionJson.getString("unionid");
////                        App.mTencent.request(Constants.GRAPH_SIMPLE_USER_INFO, null,
////                                Constants.HTTP_GET);
//                        App.mTencent.setOpenId(openid);
//                        App.mTencent.setAccessToken(access_token, expires_in);
//                        UserInfo userInfo = new UserInfo(mActivity, App.mTencent.getQQToken());
//                        userInfo.getUserInfo(new IUiListener() {
//                            @Override
//                            public void onComplete(Object o) {
//                                Log.d("ISignInPresenterCompl", "o:" + o);
//                                try {
//                                    JSONObject json = new JSONObject(o.toString());
//                                    final String nickname = json.getString("nickname");
//                                    final String figureurl_qq_1 = json.getString("figureurl_qq_1");
//                                    Log.d("ISignInPresenterCompl", nickname);
//                                    Log.d("ISignInPresenterCompl", figureurl_qq_1);
//
//                                    Call<LoginModel> thiLoginModuleCall = ApiHelper.SignInThi(nickname, figureurl_qq_1, access_token, "1");
//                                    thiLoginModuleCall.enqueue(new Callback<LoginModel>() {
//                                        @Override
//                                        public void onResponse(Call<LoginModel> call, Response<LoginModel> response) {
//                                            final LoginModel body = response.body();
//                                            String code = body.getCode();
//                                            if (code.equals("0")) {
//                                                App.preferenceUtil.putBoolean(PreferenceKey.CACHE_TOKEN, true);
//
//                                                // TODO: 2016/11/30 存储数据
//                                                LoginModel.DataBean data = body.getData();
//                                                mActivity.setRequesting(false);
//                                                mActivity.signIn(data);
//                                            } else if (code.equals("1")) {
//                                                mActivity.bindPhone(nickname, figureurl_qq_1, access_token, "1");
//                                            }
//                                        }
//
//                                        @Override
//                                        public void onFailure(Call<LoginModel> call, Throwable t) {
//                                            mActivity.runOnUiThread(new Runnable() {
//                                                @Override
//                                                public void run() {
//                                                    Toast.makeText(mActivity, "网络错误", Toast.LENGTH_SHORT).show();
//                                                }
//                                            });
//                                        }
//                                    });
//
//
//                                } catch (JSONException e) {
//                                    e.printStackTrace();
//                                    Log.d("ISignInPresenterCompl", e.toString());
//                                }
//
//
//                            }
//
//                            @Override
//                            public void onError(UiError uiError) {
//                                Log.e("ISignInPresenterCompl", "uiError:" + uiError);
//                            }
//
//                            @Override
//                            public void onCancel() {
//                                Log.d("ISignInPresenterCompl", "cancel");
//                            }
//                        });
//                    } catch (JSONException e) {
//                        e.printStackTrace();
//                        Log.d("ISignInPresenterCompl", e.toString());
//                    }
//                }
//            }.start();
//        }
//
//        @Override
//        public void onError(UiError uiError) {
//            Log.d("ISignInPresenterCompl", "uiError:" + uiError);
//        }
//
//        @Override
//        public void onCancel() {
//            Log.d("ISignInPresenterCompl", "cancel");
//        }
//    };

//    public SsoHandler getmSsoHandler() {
//        return mSsoHandler;
//    }

    @Override
    public void bindPhoneNum(final String nickName, final String pic, String phone, String code, String openId, String type) {
        Call<LoginModel> loginModelCall = ApiHelper.BindSign(nickName, pic, phone, code, openId, type);
        loginModelCall.enqueue(new Callback<LoginModel>() {
            @Override
            public void onResponse(Call<LoginModel> call, Response<LoginModel> response) {
                final LoginModel body = response.body();

                if (body.getCode().equals("0")) {
                    App.preferenceUtil.putBoolean(PreferenceKey.CACHE_TOKEN, true);

                    LoginModel.DataBean data = body.getData();
                    App.preferenceUtil.putString(PreferenceKey.SIGNHEADIMG, pic);

                    if (data.getUsername() == null || data.getUsername().length() <= 0) {
                        data.setUsername(nickName);
                    }
                    mActivity.setRequesting(false);
                    mActivity.signIn(data);
                } else {
                    mActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(mActivity, body.getMsg(), Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }

            @Override
            public void onFailure(Call<LoginModel> call, Throwable t) {
                mActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(mActivity, "网络错误", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    public ISignInPresenterCompl(SignInActivity mActivity) {
        this.mActivity = mActivity;
        String intentTag = mActivity.getIntent().getStringExtra(Constant.SIGN_JUMP_TOKEN);
        if (intentTag != null) {
            if (intentTag.equals(mActivity.fromHome)) {
                mActivity.setTag(mActivity.fromHome);
            } else if (intentTag.equals(mActivity.fromGuide)) {
                mActivity.setTag(mActivity.fromGuide);
            } else if (intentTag.equals(mActivity.fromIndividual)) {
                mActivity.setTag(mActivity.fromIndividual);
            }
        } else {
            mActivity.setTag(mActivity.fromGuide);
        }
    }

    @Override
    public void signIn(String un, String pw) {

        Call<LoginModel> call = ApiHelper.signIn(un, pw);

        call.enqueue(new Callback<LoginModel>() {
            @Override
            public void onResponse(Call<LoginModel> call, Response<LoginModel> response) {
                LoginModel loginModel = response.body();
                if (loginModel.getCode().equals("0")) {
                    App.preferenceUtil.putBoolean(PreferenceKey.CACHE_TOKEN, true);

                    // TODO: 2016/11/30 存储数据
                    LoginModel.DataBean data = loginModel.getData();
                    mActivity.setRequesting(false);
                    mActivity.signIn(data);
                } else {
                    mActivity.setRequesting(false);
                    mActivity.toas(loginModel.getMsg());
                }
            }

            @Override
            public void onFailure(Call<LoginModel> call, Throwable t) {
                mActivity.setRequesting(false);
                Log.d("request url:", "login fail");
            }
        });

    }

    @Override
    public void signIn(String platformName) {

        switch (platformName) {
//            case QQ:
//                App.mTencent.login(mActivity, "all", QQLoginListener);
//                break;
//            case WX:
//                SendAuth.Req req = new SendAuth.Req();
//                req.scope = "snsapi_userinfo";
////                    req.state = "wechat_sdk_demo_test";
//                req.state = "wechat_sign";
//                App.iwxapi.sendReq(req);
//                Log.d("ISignInPresenterCompl", "send");
//
//                break;
//            case WB:
//                AuthInfo mAuthInfo = new AuthInfo(mActivity, Constant.WEIBO_APP_KEY, Constant.REDIRECT_URL, Constant.SCOPE);
//                mSsoHandler = new SsoHandler(mActivity, mAuthInfo);
//                mSsoHandler.authorizeClientSso(new AuthListener());
//                break;
//            case ZFB:
//                if (TextUtils.isEmpty(AliConfig.PID) || TextUtils.isEmpty(AliConfig.APPID)
//                        || (TextUtils.isEmpty(AliConfig.RSA2_PRIVATE) && TextUtils.isEmpty(AliConfig.RSA2_PRIVATE))
//                        || TextUtils.isEmpty(AliConfig.TARGET_ID)) {
//                    new AlertDialog.Builder(mActivity).setTitle("警告").setMessage("需要配置PARTNER |APP_ID| RSA_PRIVATE| TARGET_ID")
//                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                                public void onClick(DialogInterface dialoginterface, int i) {
//                                }
//                            }).show();
//                    return;
//                }

                /**
                 * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
                 * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
                 * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
                 *
                 * authInfo的获取必须来自服务端；
                 */
//                String RSA2 = "";

//                new Thread() {
//                    @Override
//                    public void run() {
//                        super.run();
//                        String tempStr = String.valueOf(System.currentTimeMillis());
//                        String key = MD5Util.getMD5(tempStr + ApiHelper.deviceId);
//                        String url = ApiHelper.BASE_URL + "zfb/use-key?qweqwe&dev=" + ApiHelper.deviceId + "&need-key=" + tempStr + "&sign=" + key;
//                        String request = ApiHelper.request(url);
//                        Log.d("ISignInPresenterCompl", request);
//                        try {
//                            JSONObject jsonObject = new JSONObject(request);
//                            String code = jsonObject.getString("code");
//                            if (code.equals("0")) {
//                                JSONObject data = jsonObject.getJSONObject("data");
//                                String dataCode = data.getString("code");
//                                String dataKey = data.getString("key");
//                                String re2key = DecodeUtil.DecodeUtilRsat(dataKey, dataCode);
//                                if (re2key.equals(AliConfig.RSA2_PRIVATE)) {
//                                    boolean rsa2 = (AliConfig.RSA2_PRIVATE.length() > 0);
//                                    Map<String, String> authInfoMap = OrderInfoUtil2_0.buildAuthInfoMap(AliConfig.PID, AliConfig.APPID, AliConfig.TARGET_ID, rsa2);
//                                    String info = OrderInfoUtil2_0.buildOrderParam(authInfoMap);
//
//                                    String privateKey = rsa2 ? AliConfig.RSA2_PRIVATE : AliConfig.RSA_PRIVATE;
//                                    String sign = OrderInfoUtil2_0.getSign(authInfoMap, privateKey, rsa2);
//                                    final String authInfo = info + "&" + sign;
//                                    Runnable authRunnable = new Runnable() {
//
//                                        @Override
//                                        public void run() {
//                                            // 构造AuthTask 对象
//                                            AuthTask authTask = new AuthTask(mActivity);
//                                            // 调用授权接口，获取授权结果
//                                            Map<String, String> result = authTask.authV2(authInfo, true);
//
//                                            Message msg = new Message();
//                                            msg.what = mActivity.ZFB_AUTH_FLAG;
//                                            msg.obj = result;
//                                            mActivity.mHandler.sendMessage(msg);
//                                        }
//                                    };
//
//                                    // 必须异步调用
//                                    Thread authThread = new Thread(authRunnable);
//                                    authThread.start();
//                                } else {
//                                    Log.e("ISignInPresenterCompl", "rsa2 decode error");
//                                }
//                                Log.d("ISignInPresenterCompl", "re2key: " + re2key);
//                            }
//                        } catch (Exception e) {
//                            Log.e("ISignInPresenterCompl", e.toString());
//                        }
//                    }
//                }.start();

//                break;
            default:
                break;
        }

//        Platform weibo = ShareSDK.getPlatform(platformName);
//
//        //回调信息，可以在这里获取基本的授权返回的信息，但是注意如果做提示和UI操作要传到主线程handler里去执行
//        weibo.setPlatformActionListener(new PlatformActionListener() {
//
//            @Override
//            public void onError(Platform arg0, int arg1, Throwable arg2) {
//                // TODO Auto-generated method stub
//                arg2.printStackTrace();
//            }
//
//            @Override
//            public void onComplete(Platform arg0, int arg1, HashMap<String, Object> arg2) {
//                // TODO Auto-generated method stub
//                //输出所有授权信息
//                String s = arg0.getDb().exportData();
//                Log.d("ISignInPresenterCompl", "arg2:" + arg2);
//                mActivity.showSignIn(arg2);
//            }
//
//            @Override
//            public void onCancel(Platform arg0, int arg1) {
//                // TODO Auto-generated method stub
//
//            }
//        });
//
////        weibo.SSOSetting(false);  //设置false表示使用SSO授权方式
//
//        //authorize与showUser单独调用一个即可
////        weibo.authorize();//单独授权,OnComplete返回的hashmap是空的
//        weibo.showUser(null);//授权并获取用户信息
//        //移除授权
//        //weibo.removeAccount(true);
    }

    @Override
    public void reqeustCode(String phone, String type) {
        Call<SendSms> sendSmsCall = ApiHelper.sendSms(phone, type);
        sendSmsCall.enqueue(new Callback<SendSms>() {
            @Override
            public void onResponse(Call<SendSms> call, Response<SendSms> response) {
                SendSms body = response.body();
                try {
                    final String msg = response.body().getMsg();
                    Message message = new Message();
                    message.what = SEND_SMS;
                    Bundle bundle = new Bundle();
                    bundle.putString(Constant.SIGN_DATA, msg);
                    mActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(mActivity, msg, Toast.LENGTH_SHORT).show();
                        }
                    });
                } catch (Exception e) {
                    Log.e("ISignInPresenterCompl", e.toString());
                }
//                mActivity.mHandler.sendMessage(message);
            }

            @Override
            public void onFailure(Call<SendSms> call, Throwable t) {
                Log.d("ISignInPresenterCompl", "error");
            }
        });
    }

    @Override
    public void signUp(String phone, String code) {
        Call<CodeModel> codeModelCall = ApiHelper.signUp(phone, code);
        mActivity.progressbar();
        codeModelCall.enqueue(new Callback<CodeModel>() {
            @Override
            public void onResponse(Call<CodeModel> call, Response<CodeModel> response) {
                CodeModel body = response.body();
                if (body.getCode().equals("0")) {
                    Message msg = new Message();
                    Bundle data = new Bundle();
                    data.putString(Constant.SIGN_TOKEN, response.body().getData().getSigntoken());
                    msg.setData(data);
                    msg.what = mActivity.SIGN_TOKEN;
                    mActivity.setRequesting(false);
                    mActivity.mHandler.sendMessage(msg);
                } else {
                    Log.d("request url:", "request fail");
                    mActivity.setRequesting(false);
                    mActivity.toas(body.getMsg());
                }
            }

            @Override
            public void onFailure(Call<CodeModel> call, Throwable t) {
                Log.d("request url:", "request error");
                mActivity.progressbar();
            }
        });
    }

    @Override
    public void signUp(String signUn, String pw, String signToken) {
        Call<SignUpModel> signUpModelCall = ApiHelper.signUp(signUn, pw, signToken);
        mActivity.progressbar();
        signUpModelCall.enqueue(new Callback<SignUpModel>() {
            @Override
            public void onResponse(Call<SignUpModel> call, Response<SignUpModel> response) {
                SignUpModel body = response.body();
                if (body.getCode().equals("0")) {
                    mActivity.setRequesting(false);
                    SignUpModel.DataBean userInfo = body.getData();
                    LoginModel.DataBean data = new LoginModel.DataBean(userInfo.getId(), userInfo.getUsername(), userInfo.getEmail(),
                            userInfo.getPhone(), userInfo.getTruename(), userInfo.getIdcard(),
                            userInfo.getAge(), userInfo.getBirthday(), userInfo.getAddress(),
                            userInfo.getCity(), userInfo.getProvince(), userInfo.getCompany(),
                            userInfo.getEducation(), userInfo.getSex(), userInfo.getHeight(),
                            userInfo.getWeight(), userInfo.getRole(), userInfo.getIostoken(),
                            userInfo.getAndroidtoken(), userInfo.getStatus(), userInfo.getGroupname());


                    App.preferenceUtil.putBoolean(PreferenceKey.CACHE_TOKEN, true);

                    // TODO: 2016/11/30 存储数据
                    mActivity.setRequesting(false);
                    mActivity.signIn(data);

//                    mActivity.signUp();
                } else {
                    mActivity.setRequesting(false);
                    mActivity.toas(body.getMsg());
                    Log.d("request url:", "request fail");
                }
            }

            @Override
            public void onFailure(Call<SignUpModel> call, Throwable t) {
                mActivity.toas(mActivity.getResources().getString(R.string.common_net_error));
                Log.d("request url:", "request error");
            }
        });
    }

//    @Override
//    public void onComplete(Bundle values) {
//        Oauth2AccessToken mAccessToken = Oauth2AccessToken.parseAccessToken(values);
//        if (mAccessToken.isSessionValid()) {
//            AccessTokenKeeper
//                    .writeAccessToken(mActivity, mAccessToken);
//            String UID=mAccessToken.getUid();
//            String accessToken = mAccessToken.getToken();
//            Log.d("gaolei", "WeiBoLogin,KEY_UID:"+mAccessToken.getUid()+",KEY_ACCESS_TOKEN:"+mAccessToken.getToken());
//            Toast.makeText(mActivity,
//                    R.string.auth_success,
//                    Toast.LENGTH_SHORT).show();
//            Toast.makeText(mActivity,
//                    "WeiBoLogin,KEY_UID:"+mAccessToken.getUid()+",KEY_ACCESS_TOKEN:"+mAccessToken.getToken(),
//                    Toast.LENGTH_SHORT).show();
//        } else {
//            String code = values.getString("code");
//            String message = mActivity
//                    .getString(R.string.auth_failure);
//            if (!TextUtils.isEmpty(code)) {
//                message = message + "\ncode: " + code;
//            }
//            Toast.makeText(mActivity, message, Toast.LENGTH_SHORT)
//                    .show();
//        }
//    }

//    @Override
//    public void onWeiboException(WeiboException e) {
//        Toast.makeText(mActivity, R.string.auth_failure, Toast.LENGTH_SHORT).show();
//    }
//
//    @Override
//    public void onCancel() {
//        Toast.makeText(mActivity, R.string.auth_cancel, Toast.LENGTH_SHORT)
//                .show();
//    }

//    class AuthListener implements WeiboAuthListener {
//
//        @Override
//        public void onComplete(Bundle values) {
//            // 从 Bundle 中解析 Token
//            mAccessToken = Oauth2AccessToken.parseAccessToken(values);
//            //从这里获取用户输入的 电话号码信息
////            phoneNum = mAccessToken.getPhoneNum();
//
//            if (mAccessToken.isSessionValid()) {
//                // 显示 Token
////                updateTokenView(false);
//
//                // 保存 Token 到 SharedPreferences
//                AccessTokenKeeper.writeAccessToken(mActivity, mAccessToken);
//                Toast.makeText(mActivity,
//                        "获取成功", Toast.LENGTH_SHORT).show();
//
//                Oauth2AccessToken oauth2AccessToken = AccessTokenKeeper.readAccessToken(mActivity);
//                final long uid = Long.parseLong(oauth2AccessToken.getUid());
//                // TODO: 2017/2/14 获取uid
//                String token = oauth2AccessToken.getToken();
//                Log.d("AuthListener", "uid:" + uid);
//                final String wbUrl = ApiHelper.getWBUserInfo(token, uid);
//                Log.d("AuthListener", wbUrl);
//                final OkHttpClient client = new OkHttpClient();
//                new Thread() {
//                    @Override
//                    public void run() {
//                        Request request = new Request.Builder()
//                                .url(wbUrl)
//                                .build();
//                        try {
//                            okhttp3.Response response = client.newCall(request).execute();
//                            String json = response.body().string();
//                            try {
//                                JSONObject jsonObject = new JSONObject(json);
//                                Log.d("AuthListener", jsonObject.toString());
//                                final String name = jsonObject.getString("name");
//                                final String profile_image_url = jsonObject.getString("profile_image_url");
//                                Log.d("AuthListener", name);
//                                Log.d("AuthListener", profile_image_url);
//
//                                Call<LoginModel> loginModelCall = ApiHelper.SignInThi(name, profile_image_url, String.valueOf(uid), "2");
//                                loginModelCall.enqueue(new Callback<LoginModel>() {
//                                    @Override
//                                    public void onResponse(Call<LoginModel> call, Response<LoginModel> response) {
//                                        LoginModel body = response.body();
//                                        Log.d("AuthListener", body.getCode());
//                                        if (body.getCode().equals("0")) {
////                                            Log.d("AuthListener", body.getData().getPic());
//                                            mActivity.signIn(body.getData());
//                                        } else {
//                                            mActivity.bindPhone(name, profile_image_url, String.valueOf(uid), "2");
//                                        }
//                                    }
//
//                                    @Override
//                                    public void onFailure(Call<LoginModel> call, Throwable t) {
//                                        mActivity.netErrorToast();
//                                    }
//                                });
//
//                            } catch (JSONException e) {
//                                Log.e("AuthListener", e.toString());
//                            }
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }.start();
//
//            } else {
//                // 以下几种情况，您会收到 Code：
//                // 1. 当您未在平台上注册的应用程序的包名与签名时；
//                // 2. 当您注册的应用程序包名与签名不正确时；
//                // 3. 当您在平台上注册的包名和签名与您当前测试的应用的包名和签名不匹配时。
//                String code = values.getString("code");
//                String message = "fail";
//                if (!TextUtils.isEmpty(code)) {
//                    message = message + "\nObtained the code: " + code;
//                }
//                Toast.makeText(mActivity, message, Toast.LENGTH_LONG).show();
//            }
//        }
//
//        @Override
//        public void onCancel() {
//            Toast.makeText(mActivity,
//                    "取消", Toast.LENGTH_LONG).show();
//        }
//
//        @Override
//        public void onWeiboException(WeiboException e) {
//            Toast.makeText(mActivity,
//                    "Auth exception : " + e.getMessage(), Toast.LENGTH_LONG).show();
//        }
//    }
}
